package jp.co.sharp.android.parents.kidsguard.activity.profile;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.bluetooth.BluetoothSearchActivity;
import jp.co.sharp.android.parents.kidsguard.activity.common.MimamoriBusinessService;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.OpenBluetoothConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.PermissionDlg;
import jp.co.sharp.android.parents.kidsguard.common.StatueSelectDlg;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothItemDto;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;


/**
 * プロフィール編集
 */
public class ProfileEditActivity extends Activity {

    private EditText mEditText;
    // パージ使用するには
    private BluetoothItemDto mPageBluetoothItemDto;
    private final int REQUEST_CODE = 100;
    private ImageView mImageView;
    private OldProfileInfo mOldProfileInfo;
    // Camera
    private final static int CAMERA = 0;
    // Album
    private final static int ALBUM = 1;
    // 権限CODE
    private final static int CAMERA_PERMISSION_CODE = 1;
    private final static int ALBUM_PERMISSION_CODE = 2;
    private final static int REQ_PERMISSION_RESULT = 3;
    // 0: Camera  1:Album
    private int mCurrentSel = 0;
    private static final String TAG = "TAG";
    private boolean mUnReceiver = false;
    private App mApp;
    private MimamoriBusinessService mMimamoriBusinessService;
    private String mAction;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "ProfileEditActivity_onCreate");
        setContentView(R.layout.activity_profile_edit);

        mApp = (App)getApplication();
        initActivity();
        mMimamoriBusinessService = new MimamoriBusinessService(ProfileEditActivity.this,
                mApp, new Intent(getIntent()), (NotificationManager)getSystemService(NOTIFICATION_SERVICE));
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ProfileEditActivity_onStart");
        synchronized (mSyncLock) {
            mMimamoriBusinessService.registerReceiver();
            mUnReceiver = false;
            mApp.setAppStatus(Constants.APP_STATUS_INIT);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ProfileEditActivity_onStop");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        mMimamoriBusinessService.unRegisterSystemReceiver();
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                try {
                    mMimamoriBusinessService.unRegisterReceiver();
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ProfileEditActivity_onDestroy");
        synchronized (mSyncLock) {
            if (!mUnReceiver) {
                if (mPageJumpFlag) {
                    try {
                        mMimamoriBusinessService.unRegisterSystemReceiver();
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                try {
                    mMimamoriBusinessService.unRegisterReceiver();
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                mUnReceiver = true;
            }
        }
    }

    /**
     * init page
     */
    private void initActivity() {
        Log.i(TAG, "ProfileEditActivity_initActivity");
        Intent intent = getIntent();
        mAction = intent.getAction();
        mEditText = (EditText)findViewById(R.id.newBluetoothName);
        TextView textView = (TextView)findViewById(R.id.bluetoothName);
        Button button = (Button)findViewById(R.id.saveNewBluetoothName);
        mImageView = (ImageView)findViewById(R.id.imgKidAvatar);

        if (null == mAction || mAction.equals(Constants.ACTION_ADD_BLUETOOTH) || mAction.equals(Constants.ACTION_KID_BLUETOOTH)) {
            mEditText.setText("");
            mPageBluetoothItemDto = (BluetoothItemDto)intent.getSerializableExtra(Constants.KEY_ADD_BLUETOOTH);
            textView.setText(mPageBluetoothItemDto.getBluetoothName());
            /*button.setEnabled(false);*/
        } else {
            // Home パージから
            mPageBluetoothItemDto = (BluetoothItemDto)intent.getSerializableExtra(Constants.KEY_EDIT_BLUETOOTH);
            textView.setText(mPageBluetoothItemDto.getBluetoothName());
            mEditText.setText(mPageBluetoothItemDto.getDeviceNickName());
        }

        if (null != mPageBluetoothItemDto.getKidAvatar()) {
            Uri uri = Uri.fromFile(new File(mPageBluetoothItemDto.getKidAvatar()));
            mImageView.setImageURI(uri);
        }

        mOldProfileInfo = new OldProfileInfo();
        if (null == mOldProfileInfo.mBluetoothItemDto) {
            try {
                mOldProfileInfo.mBluetoothItemDto = (BluetoothItemDto)this.mPageBluetoothItemDto.clone();
            } catch (Exception e) {

            }
        }

        ImageView imageView = (ImageView)findViewById(R.id.clearNewBluetoothName);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEditText.setText("");
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ページジャンプ
                mPageJumpFlag = true;
                mPageBluetoothItemDto.setDeviceNickName(mEditText.getText().toString());
                Intent intent1 = new Intent();
                if (null == mAction || mAction.equals(Constants.ACTION_ADD_BLUETOOTH) || mAction.equals(Constants.ACTION_KID_BLUETOOTH)) {
                    intent1.setAction(Constants.ACTION_ADD_BLUETOOTH);
                    intent1.putExtra(Constants.KEY_ADD_BLUETOOTH, mPageBluetoothItemDto);
                } else {
                    intent1.setAction(mAction);
                    intent1.putExtra(Constants.KEY_EDIT_BLUETOOTH, mPageBluetoothItemDto);
                }
                intent1.setClass(ProfileEditActivity.this, HomeActivity.class);
                startActivity(intent1);
            }
        });
        //
        ImageButton imageButton = (ImageButton)findViewById(R.id.imgBtnEditProfile);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StatueSelectDlg statueSelectDlg = new StatueSelectDlg(ProfileEditActivity.this, R.style.commonDlg);
                statueSelectDlg.show();
                statueSelectDlg.setOnCameraSetListener(new StatueSelectDlg.OnCameraSetListener() {
                    @Override
                    public void onOperateSet() {
                        statueSelectDlg.dismiss();
                        // Camera
                        initPermissions(CAMERA);
                    }
                });
                statueSelectDlg.setOnAlbumSetListener(new StatueSelectDlg.OnAlbumSetListener() {
                    @Override
                    public void onOperateSet() {
                        statueSelectDlg.dismiss();
                        // Album
                        initPermissions(ALBUM);
                    }
                });

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.i(TAG, "ProfileEditActivity_onActivityResult");
        if (requestCode == REQUEST_CODE) {
            if (null != intent && intent.hasExtra(Constants.KEY_KID_IMAGE_URL) && null != intent.getStringExtra(Constants.KEY_KID_IMAGE_URL)) {
                String kidImageUrl = intent.getStringExtra(Constants.KEY_KID_IMAGE_URL);
                Uri uri = Uri.fromFile(new File(kidImageUrl));
                mImageView.setImageDrawable(null);
                mImageView.setImageURI(uri);
                mPageBluetoothItemDto.setKidAvatar(kidImageUrl);
            }
        } else if (requestCode == REQ_PERMISSION_RESULT) {
            initPermissions(mCurrentSel);
        } else if (requestCode == RequestCodeConstants.MIMAMORI_CONTACT_ADD) {
            // Mimamori Add Contact
            mMimamoriBusinessService.onContactAddResult(true);
        }
    }

    class OldProfileInfo {
        BluetoothItemDto mBluetoothItemDto;
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        Log.i(TAG, "ProfileEditActivity_backActivity");
        this.mPageBluetoothItemDto.setDeviceNickName(mEditText.getText().toString());

        Intent intent = new Intent();
        if (mAction.equals(Constants.ACTION_ADD_BLUETOOTH) || mAction.equals(Constants.ACTION_KID_BLUETOOTH)) {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!bluetoothAdapter.isEnabled()) {
                // Bluetoothがオンになっていない
                OpenBluetoothConfirmDlg openBluetoothConfirmDlg = new OpenBluetoothConfirmDlg(ProfileEditActivity.this, R.style.commonDlg);
                openBluetoothConfirmDlg.show();
                openBluetoothConfirmDlg.setOnOperateSetListener(new OpenBluetoothConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        openBluetoothConfirmDlg.dismiss();
                        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)); //直接进入手机中的蓝牙设置界面
                    }
                });
            } else {
                String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
                DelDeviceConfirmDlg delDeviceConfirmDlg = new DelDeviceConfirmDlg(ProfileEditActivity.this, R.style.commonDlg, message);
                delDeviceConfirmDlg.show();
                delDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        delDeviceConfirmDlg.dismiss();
                        mMimamoriBusinessService.unRegisterReceiver();
                        mUnReceiver = true;
                        // ページジャンプ
                        mPageJumpFlag = true;
                        intent.setAction(mAction);
                        intent.setClass(ProfileEditActivity.this, BluetoothSearchActivity.class);
                        intent.putExtra(Constants.KEY_KID_MAC_ADDRESS, mPageBluetoothItemDto.getMacAddress());
                        startActivity(intent);
                    }
                });
            }
        } else {
            if (mOldProfileInfo.mBluetoothItemDto.equals(this.mPageBluetoothItemDto)) {
                intent.setClass(ProfileEditActivity.this, HomeActivity.class);
                startActivity(intent);
            } else {
                String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
                DelDeviceConfirmDlg delDeviceConfirmDlg = new DelDeviceConfirmDlg(ProfileEditActivity.this, R.style.commonDlg, message);
                delDeviceConfirmDlg.show();
                delDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                    @Override
                    public void onOperateSet() {
                        delDeviceConfirmDlg.dismiss();
                        mMimamoriBusinessService.unRegisterReceiver();
                        mUnReceiver = true;
                        // ページジャンプ
                        mPageJumpFlag = true;
                        intent.setClass(ProfileEditActivity.this, HomeActivity.class);
                        startActivity(intent);
                    }
                });
            }
        }
    }

    /**
     * 権限を確認してください
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void initPermissions(int pFlag) {
        Log.i(TAG, "ProfileEditActivity_initPermissions");
        mCurrentSel = pFlag;
        if (pFlag == CAMERA) {
            // Camera
            // Android バージョン番号
            int version = android.os.Build.VERSION.SDK_INT;
            if (version >= 23) {
                if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) ||
                        (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_PERMISSION_CODE);
                } else {
                    initAvatarProcess(pFlag);
                }
            } else {
                initAvatarProcess(pFlag);
            }
        } else if (pFlag == ALBUM) {
            // Album
            // Android バージョン番号
            int version = android.os.Build.VERSION.SDK_INT;
            if (version >= 23) {
                if ((checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) ||
                        (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                    requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE}, ALBUM_PERMISSION_CODE);
                } else {
                    initAvatarProcess(pFlag);
                }
            } else {
                initAvatarProcess(pFlag);
            }
        }

    }

    /**
     * 権限を確認してください
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "ProfileEditActivity_onRequestPermissionsResult");
        Boolean phonePermissionFlag = false;
        Boolean storagePermissionFlag = false;
        if (requestCode == this.CAMERA_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                phonePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[0])){
                    Toast.makeText(this, "Cameraの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(ProfileEditActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            startActivityForResult(intent,1000);
                        }
                    });
                }
            }
            if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                storagePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[1])){
                    Toast.makeText(this, "Cameraの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(ProfileEditActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            permissionDlg.dismiss();
                            startActivityForResult(intent, REQ_PERMISSION_RESULT);
                        }
                    });
                }
            }
        } else if (requestCode == this.ALBUM_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                phonePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[0])){
                    Toast.makeText(this, "Media Storageの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(ProfileEditActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            startActivityForResult(intent,1000);
                        }
                    });
                }
            }
            if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                storagePermissionFlag = true;
            } else {
                if (shouldShowRequestPermissionRationale(permissions[1])){
                    Toast.makeText(this, "Media Storageの権限が必要です。アクセス権限を付与してください", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:jp.co.sharp.android.parents.kidsguard"));
                    PermissionDlg permissionDlg = new PermissionDlg(ProfileEditActivity.this, R.style.commonDlg);
                    permissionDlg.show();
                    permissionDlg.setOnOperateSetListener(new PermissionDlg.OnOperateSetListener() {
                        @Override
                        public void onOperateSet() {
                            permissionDlg.dismiss();
                            startActivityForResult(intent, REQ_PERMISSION_RESULT);
                        }
                    });
                }
            }
        }
        if(storagePermissionFlag && phonePermissionFlag) {
            initAvatarProcess(mCurrentSel);
        }
    }


    /**
     * 許可を確認した
     */
    private void initAvatarProcess(int pFlag) {
        Log.i(TAG, "ProfileEditActivity_initAvatarProcess");
        if (pFlag == CAMERA) {
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent1 = new Intent();
            intent1.setClass(ProfileEditActivity.this, ProfileCameraActivity.class);
            intent1.putExtra(Constants.KEY_KID_IMAGE_NAME, mPageBluetoothItemDto.getMacId());
            startActivityForResult(intent1, REQUEST_CODE);
        } else if (pFlag == ALBUM) {
            // ページジャンプ
            mPageJumpFlag = true;
            Intent intent1 = new Intent();
            intent1.setClass(ProfileEditActivity.this, ProfileClipActivity.class);
            intent1.putExtra(Constants.KEY_KID_IMAGE_NAME, mPageBluetoothItemDto.getMacId());
            startActivityForResult(intent1, REQUEST_CODE);
        }
    }
}
